package org.demo.treeeditor.mode;

import java.awt.event.KeyEvent;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.demo.treeeditor.StateMachine;

public abstract class AbstractMode implements Modeable{

	StateMachine stateMachine;
	List<String> keyAssignment = new ArrayList<String>();
	
	public AbstractMode(StateMachine stateMachine){
		this.stateMachine = stateMachine;
		init();
	}

	abstract public void init();

	Map<Integer,String> actions = new HashMap<Integer,String>();
	
	void setAction(String string, String action) {
		Integer keycode = stringToKeyCode(string); 
		System.out.println("setting..."+keycode);
		actions.put(keycode, action);
		keyAssignment.add(string+" "+action);
		
	}
	
	void setAction(Integer keyCode, String action) {
		System.out.println("setting..."+keyCode);
		actions.put(keyCode, action);
		
	}
	
	Integer stringToKeyCode(String string) {
		return (int)string.charAt(0);
	}

	public void handleEvent(KeyEvent e) {


		String action = actions.get(e.getKeyCode());
		if(action!=null){
			try {
				Method m = this.getClass().getDeclaredMethod(action,new Class[0]);
				m.invoke(this);
			} catch (SecurityException e1) {
				e1.printStackTrace();
			} catch (NoSuchMethodException e1) {
				e1.printStackTrace();
			} catch (IllegalArgumentException e1) {
				e1.printStackTrace();
			} catch (IllegalAccessException e1) {
				e1.printStackTrace();
			} catch (InvocationTargetException e1) {
				e1.printStackTrace();
			}
		}else{
			handleOtherEvent(e);
		}

	}
	
	public void handleOtherEvent(KeyEvent e){
		System.out.println("nothing to do onKeyPressed:" + e.getKeyCode()+" "+e.getKeyText(e.getKeyCode())+" "+e.getKeyChar());
	}
	
	public List<String> getKeyAssignment(){
		return keyAssignment;
	};
	
	
	
	
}
